package com.greenlife.controller.util;

import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.authz.UnauthorizedException;
import org.slf4j.Logger;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import com.greenlife.commom.ResponseException;
import com.greenlife.common.enums.BaseResultCodeEnum;
import com.greenlife.common.result.CommonResult;

public class ControllerErrorProcessor {
    /**
     * 入参异常检查
     * @param resultList
     * @param errorParams 需要捕获的错误码
     */
    public static void paramErrorProcessor(BindingResult resultList, String... errorParams) {
        List<String> errorParamList = new ArrayList<String>();
        for (String errorParam : errorParams) {
            errorParamList.add(errorParam);
        }
        if (resultList.hasErrors()) {
            List<ObjectError> errorList = resultList.getAllErrors();
            for (ObjectError error : errorList) {
                if (errorParamList.contains(error.getDefaultMessage()))
                    throw new ResponseException(BaseResultCodeEnum.valueOf(error
                        .getDefaultMessage()));
            }
        }
    }

    public static CommonResult exceptionProcessor(Exception ex, Logger logger) {
        if (ex instanceof ResponseException) {
            ResponseException re = (ResponseException) ex;
            logger.warn("操作失败:" + re.getExceptionEnums().toString());
            return ResponseException.buildException(re);
        } else if (ex instanceof UnauthorizedException) {
        	UnauthorizedException re = (UnauthorizedException) ex;
            logger.warn("无权限进行该操作:" + re.toString());
            return ResponseException.buildException(new ResponseException(BaseResultCodeEnum.ERR_CODE_00005));
        } else {
            logger.error("系统异常:" + ex.getMessage());
            return ResponseException.buildException(new ResponseException(
                BaseResultCodeEnum.ERR_CODE_00000));
        }
    }
}
